package view;
import java.awt.*;
import java.io.*;

import javax.imageio.*;
import javax.swing.*;
import javax.swing.border.*;

import model.Card;
import model.CardStack;
import model.GameModel;
import model.TableModel;

import java.util.*;

public class TableComponent extends JComponent{
	private GameModel model;
	public TableComponent(GameModel model) {
		this.model = model;
	}
	public Dimension getPreferredSize() {
		return new Dimension(400, 400); //(350, 350)
	}
	public void paint(Graphics tg) {
		Graphics2D g = (Graphics2D)tg;
		g.setColor(new Color(0, 100, 0));
		g.fillRect(0, 0, getWidth(), getHeight());
	
		for(CardStack stack: model.getTableCards()) {
			int xpos = stack.x;
			int ypos = stack.y;
	
			for(Card card: stack.getAll()) {
				g.drawImage(ImageLoader.loadImage(card), 
						xpos-ImageLoader.IMAGE_WIDTH/2, ypos-ImageLoader.IMAGE_HEIGHT/2, null);
				
				if (card.isHighlighted())
				{
					g.setStroke(new BasicStroke(5));
					g.setColor(Color.YELLOW);
					g.drawRect(xpos-ImageLoader.IMAGE_WIDTH/2, ypos-ImageLoader.IMAGE_HEIGHT/2, ImageLoader.IMAGE_WIDTH, ImageLoader.IMAGE_HEIGHT);
				}
				
				xpos+=1;
				ypos+=1;
		
			}
		}
	}
	
	public GameModel getGameModel()
	{
		return model;
	}
	
	/**
	 * Finds the card that is painted at the given location. 
	 * Currently the algorithm is just to brute force search over all stacks on the table.
	 * May need to improve this algorithm for better performance.
	 */
	public Card getCardAt(int x, int y) {
		//System.out.println("size of all cards" + model.getTableCards().size());
		for(CardStack stack: model.getTableCards()) {
			if(x < stack.x - ImageLoader.IMAGE_WIDTH/2 ||
					x > stack.x + stack.getSize() + ImageLoader.IMAGE_WIDTH/2 ||
					y < stack.y - ImageLoader.IMAGE_HEIGHT/2 ||
					y > stack.y + stack.getSize() + ImageLoader.IMAGE_HEIGHT/2)
				continue;
			//for now just return the top card..... too lazy to work out the math to return the correct card in stack
			return stack.get(stack.getSize()-1);
		}
		return null;
	}
	
	public CardStack getStackAt(int x, int y)
	{
		for(CardStack stack: model.getTableCards()) {
			if(x < stack.x - ImageLoader.IMAGE_WIDTH/2 ||
					x > stack.x + stack.getSize() + ImageLoader.IMAGE_WIDTH/2 ||
					y < stack.y - ImageLoader.IMAGE_HEIGHT/2 ||
					y > stack.y + stack.getSize() + ImageLoader.IMAGE_HEIGHT/2)
				continue;
			//for now just return the top card..... too lazy to work out the math to return the correct card in stack
			return stack;
		}
		return null;
		
		
	}
	
	public void shuffleStack(CardStack stack)
	{
		stack.shuffle();
	}
}